//
//  WmcDecibeLabel.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/21.
//

import UIKit

public extension WmcDecibeLabel {
    enum Format: Int {
        /// 正整数分贝 0 ~ 120
        case positiveDB

        /// 描述分贝
        case describeDB

        /// 带符号分贝 -120 ~ 0
        case symbolDB

        /// 偏移量db -60 ~ 60
        case offsetDB
    }
}

// MARK: - [WmcDecibeLabel]

open class WmcDecibeLabel: WmcBaseSystemFieldLabel {
    // Open

    /// 显示格式
    open var format: Format = .describeDB {
        didSet { showText() }
    }

    /// 配置
    override open func config() {
        text = "获取噪音数据..."

        // 开始订阅
        WmcDecibeManager.shared.decibeRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self,
                  !weakSelf.styleMode.isStatic else { return }
            weakSelf.updateDecibe(value)
        }).disposed(by: rx.disposeBag)
    }

    // Internal

    var currentDecibe: Double = 0

    /// 子类获取时间的方法
    func updateDecibe(_ decibe: Double) {
        YPGCD.Main { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.currentDecibe = decibe
            weakSelf.showText()
        }
    }

    /// 显示文字
    func showText() {
        let microphoneStauts = WmcAuthorizedManager.microphone()
        if microphoneStauts.info.isAvailable {
            var str = ""
            // 直接转format
            switch format {
            case .positiveDB:
                let positiveDB = Int(currentDecibe + 120)
                str = "\(positiveDB)分贝"
            case .describeDB:
                str = WmcWatermarkUtil.describeDBStr(for: currentDecibe)
            case .symbolDB:
                let symbolDB = Int(currentDecibe)
                str = "\(symbolDB)"
            case .offsetDB:
                let offsetDB = Int(currentDecibe + 60)
                str = "\(offsetDB)分贝"
            }
            text = str
        } else {
            text = "未开启麦克风权限"
        }
    }

}
